package cn.shangqizhenshuai.core;

import cn.shangqizhenshuai.entity.JavaEntity;
import cn.shangqizhenshuai.entity.TableEntity;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;

public class ExampleExecute extends ExecuteCore {

    @Override
    public HashMap<String, List> execute(HashMap<String, List> context) throws IOException, TemplateException {
        //从上下文中获取表信息
        List<TableEntity> selecttabcolumn = context.get("tabinfo");
        //实体信息
        List<JavaEntity> entityinfo = context.get("entityinfo");
        //导入模板目录
        File file = new File("src/main/resources/");
        //配置模板文件对象
        Configuration conf=new Configuration();
        conf.setDirectoryForTemplateLoading(file);
        Template temp = conf.getTemplate(this.getFTLname());
        //开始文件路径输出
        String packagename = this.getPackagename();
        String[] split = packagename.split("\\.");
        String outpath = "src/main/java/"+this.getOutFilePath();
        for (String s : split) {
            outpath +="/"+s;
        }
        //创建文件夹
        File file1 = new File(outpath);
        file1.mkdirs();
        //开始循环输出文件
        for (JavaEntity javaEntity : entityinfo) {
            Writer out=new FileWriter(new File(outpath+"/"+javaEntity.getJavaname()+"Example.java"),false);
            temp.process(javaEntity, out);
            out.flush();
            out.close();
        }

        return context;
    }
}
